package top.pengdong.pictureShare.tweet.aspect;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.pengdong.pictureShare.common.model.R;
import top.pengdong.pictureShare.common.model.SysConstant;
import top.pengdong.pictureShare.tweet.dao.PsCountDao;
import top.pengdong.pictureShare.tweet.entity.PsCommentEntity;
import top.pengdong.pictureShare.tweet.entity.PsCount;
import top.pengdong.pictureShare.tweet.handle.ListenHandler;
import top.pengdong.pictureShare.tweet.service.PsTweetService;
import top.pengdong.pictureShare.tweet.utils.RedisUtil;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wl
 * @date 2022/2/22
 */
//指定为切面类
@Slf4j
@Aspect
@Component
public class TweetAspect {
    private final PsTweetService psTweetService;
    private final RedisUtil redisUtil;
    private final PsCountDao psCountDao;

    public static PsCount psCount;

    @Autowired
    public TweetAspect(PsTweetService psTweetService, RedisUtil redisUtil, PsCountDao psCountDao) {
        this.psTweetService = psTweetService;
        this.redisUtil = redisUtil;
        this.psCountDao = psCountDao;
    }

    @PostConstruct
    public void init() {
        // 数据量记录统计
        log.info("进行当日点击量处理操作");
        String today= DateUtil.today();
        Integer id = Integer.valueOf(today.replace("-", ""));
        TweetAspect.psCount = (PsCount) redisUtil.hget(SysConstant.COUNT_SUM, String.valueOf(id));
        if (psCount == null) {
            TweetAspect.psCount = new PsCount();
            psCount.setId(id);
            psCount.setCommentCount(0);
            psCount.setCollectionCount(0);
            psCount.setLikeCount(0);
            psCount.setViewCount(0);
            psCount.setForwardCount(0);
            psCount.setCreateTime(new Date());
            redisUtil.hset(SysConstant.COUNT_SUM, String.valueOf(id), TweetAspect.psCount);
            psCountDao.insert(TweetAspect.psCount);
        }
        log.info("进行单日点击量处理操作完毕");


        // 进行redis 初始化工作 防止中间断层没有数据进行更新
        for (int i = 1; i < 7; ++i) {
            if (redisUtil.hget(SysConstant.COUNT_SUM, String.valueOf(id - i)) == null) {
                PsCount psCount = new PsCount();
                psCount.setId(id - i);
                psCount.setCommentCount(0);
                psCount.setCollectionCount(0);
                psCount.setLikeCount(0);
                psCount.setViewCount(0);
                psCount.setForwardCount(0);
                psCount.setCreateTime(new Date());
                redisUtil.hset(SysConstant.COUNT_SUM, String.valueOf(id - i), TweetAspect.psCount);
                // psCountDao.insert(TweetAspect.psCount);
            }
        }
    }

    /**
     * 关闭时候写入数据库
     */
    @PreDestroy
    public void end() {
        log.info("数据库写入访问量记录操作");
        psCountDao.updateById(TweetAspect.psCount);
    }

    // 浏览量记录操作
    @Before("execution( * top.pengdong.pictureShare.tweet.controller.PsTweetController.tweet_info(..))")
    public void addTweetView(JoinPoint joinPoint) throws Throwable {
        Object[] objs=joinPoint.getArgs();
        Long aid=(Long) objs[0];

        System.out.println( "切面测试 浏览记录" + aid);
        //根据id更新点赞量
        //TODO 后面应该换成redis 进行记录操作的 目前使用 mysql 进行记录操作
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("id",aid);
        wrapper.setSql("`view_count` = `view_count` + 1");
        psTweetService.update(wrapper);

        // redisUtil.zIncrementScore(ListenHandler.LIKE_KEY,aid.toString(),1);

        // 访问量记录
        psCount.setViewCount(psCount.getViewCount() + 1);
        redisUtil.hset(SysConstant.COUNT_SUM, String.valueOf(TweetAspect.psCount.getId()), TweetAspect.psCount);
    }



    // 点赞评论操作
    @AfterReturning(returning = "data", pointcut = "execution( * top.pengdong.pictureShare.tweet.controller.PsTweetController.user_action(..))")
    public Object doLikeAfter(JoinPoint joinPoint, Object data) throws Throwable {
        Object[] objs=joinPoint.getArgs();
        String action=(String) objs[0];
        String type=(String) objs[1];
        Long aid=(Long) objs[2];
        // System.out.println( "切面测试" + aid);
        //根据id更新点赞量
        //TODO 后面应该换成redis 进行记录操作的
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", aid);
        R r = (R) data;
        if ((Integer) r.get("code") == 200) {
            // System.out.println("切面测试 R 返回值" + r.get("code"));
            if ("collection".equals(type)) {
                if ("add".equals(action)) {
                    updateWrapper.setSql("`collection_count` = `collection_count` + 1");
                } else {
                    updateWrapper.setSql("`collection_count` = `collection_count` - 1");
                }
            } else {
                if ("add".equals(action)) {
                    updateWrapper.setSql("`like_count` = `like_count` + 1");
                } else {
                    updateWrapper.setSql("`like_count` = `like_count` - 1");
                }
            }
            psTweetService.update(updateWrapper);
            redisUtil.hset(SysConstant.COUNT_SUM, String.valueOf(TweetAspect.psCount.getId()), TweetAspect.psCount);

        }

        // 访问量记录
        psCount.setLikeCount(psCount.getLikeCount() + 1);
        redisUtil.hset(SysConstant.COUNT_SUM, String.valueOf(TweetAspect.psCount.getId()), TweetAspect.psCount);

        // 记得要进行返回
        return data;
        // redisUtil.zIncrementScore(ListenHandler.LIKE_KEY,aid.toString(),1);
    }

    // 评论记录
    @AfterReturning(returning = "data",
            pointcut = "execution( * top.pengdong.pictureShare.tweet.controller.PsCommentController.comment_add(..))")
    public Object doCommentAfter(JoinPoint joinPoint, Object data) throws Throwable {
        Object[] objs=joinPoint.getArgs();
        PsCommentEntity psComment=(PsCommentEntity) objs[0];
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", psComment.getTweetId());
        R r = (R) data;
        if ((Integer) r.get("code") == 200) {
            updateWrapper.setSql("`comment_count` = `comment_count` + 1");
            psTweetService.update(updateWrapper);
        }

        // 访问量记录
        psCount.setCommentCount(psCount.getCommentCount() + 1);
        redisUtil.hset(SysConstant.COUNT_SUM, String.valueOf(TweetAspect.psCount.getId()), TweetAspect.psCount);

        return data;
    }

    // 转发记录
    @Before("execution( * top.pengdong.pictureShare.tweet.controller.PsTweetController.shareTweet(..))")
    public void doShareAfter(JoinPoint joinPoint) throws Throwable {
        Object[] objs=joinPoint.getArgs();
        Long aid=(Long) objs[0];

        // System.out.println( "切面测试 浏览记录" + aid);
        //根据id更新点赞量
        //TODO 后面应该换成redis 进行记录操作的 目前使用 mysql 进行记录操作
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("id",aid);
        wrapper.setSql("`forward_count` = `forward_count` + 1");
        psTweetService.update(wrapper);

        // 访问量记录
        psCount.setForwardCount(psCount.getForwardCount() + 1);
        redisUtil.hset(SysConstant.COUNT_SUM, String.valueOf(TweetAspect.psCount.getId()), TweetAspect.psCount);

    }

}